﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Web.Services.Protocols;

namespace SPWebShell.cmdlet
{
    [Cmdlet(VerbsCommon.Remove, "SPPermissions")]
    public class RemoveSPPermission : CmdLetBase
    {
        [Parameter(Mandatory = true, HelpMessage = "The absolute URL to the SharePoint site collection. e.g. http://server/sites/SiteA/")]
        [ValidateNotNullOrEmpty]
        public string Url { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "The name of the List or document library. If this is specified then permissions for this List is removed")]
        [ValidateNotNullOrEmpty]
        public string ListName { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "The login of the user whose permissions are to be removed. If User is specified then Group should be blank")]
        [ValidateNotNullOrEmpty]
        [Alias("login" , "username")]
        public string User { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "The name of the Group whose permissions are to be removed. If Group is specified then User should be blank")]
        [ValidateNotNullOrEmpty]
        [Alias( "groupname")]
        public string Group { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                VerboseLogger("Start time: " + DateTime.Now.ToString());
                VerboseLogger(string.Format("Url:{0}", this.Url));
                ISPRepository repos = base.SPRepos;
                VerboseLogger("Resolving container site from supplied URL");
                string urlContainerSite = repos.GetContainerWebFromDocLibUrl(this.Url);
                VerboseLogger("Container url:" + urlContainerSite);
                repos.RemovePermissions(urlContainerSite, this.ListName, this.User, this.Group);
                VerboseLogger("End");
                base.ProcessRecord();
            }
            catch (SoapException ex)
            {
                string message = ex.Detail.OuterXml;
                throw new Exception(message, ex);
            }
            finally
            {
                WriteVerbose("End time: " + DateTime.Now.ToString());
            }
        }

    }
}
